package adv10;

import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class SearchXML {

	public static void main(String[] args) throws Exception {
		SAXReader re = new SAXReader();
		Document doc = re.read(new File("products.xml"));
		Scanner in = new Scanner(System.in);
		System.out.println("请输入商品号：");
		String itemNo = in.next();
		System.out.println("购买数量：");
		int num = in.nextInt();
		// String search = "/shop/product[itemno=" + itemNo + "]";
		String s2 = String.format("/shop/product[itemno=%s][stockcount>=%d]",
				itemNo, num);
		System.out.println(s2);
		Element e = (Element) doc.selectSingleNode(s2);
		if (e == null) {
			System.out.println("没有此商品或者数量不够");
		} else {
			System.out.println("折扣：" + e.attributeValue("discount"));
			System.out.println(e.element("name").getText());
			int oldNum = Integer.parseInt(e.element("stockcount").getText());

			e.element("stockcount").setText(String.valueOf(oldNum - num));
			// 把修改后的document对象写入文件
			OutputFormat f = OutputFormat.createPrettyPrint();
			f.setEncoding("utf-8");
			XMLWriter xm = new XMLWriter(new FileWriter("products.xml"), f);
			xm.write(doc);
			xm.close();
		}
	}
}
